package com.extra;

import java.util.*;

public class Solution129 {
    List<String> list = new ArrayList<>();
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        getNum(root);
        int sum = 0;
        for (String str : list) {
            sum += Integer.parseInt(str);
        }
        return sum;
    }

    StringBuffer sb = new StringBuffer();
    public void getNum(TreeNode root) {
        sb.append(root.val);
        if (root.left == null && root.right == null) {
            list.add(sb.toString());
            return;
        }
        if (root.left != null) {
            getNum(root.left);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (root.right != null) {
            getNum(root.right);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}